// @title jQuery CSS Sprites :
// @requires Object.beget, jquery
// @author Clark Van Oyen

$.sprite = function(opts){
    return $("<div></div>").sprite(opts);
};

$.extend($.sprite, {
    
    // options to be used on the automatic $().ready() initiated call of $.sprite.init.
    // and as defaults where not specified.
    defaults: {
        sprite_class: 'css-sprite',
        img_prefix: '/media/img/',
        img_suffix: '-sprite.png',
        img_spec: null // should be of the form <imagename>|<index> ie) media|1
    },
    
    init: function(opts){
        opts = $.extend({},$.sprite.defaults, opts || {});
        $('.'+opts.sprite_class).sprite(opts);
    },
    
    info: {
        defaults: {
            img_full_path:'', //override as an alterative image url mechanism (vs opts)
            sprite_width:3200,
            img_width:32,
            img_height:32
        }
    }
});

// initialize on $().ready();
$().ready($.sprite.init);

// make an element into a sprite.
$.fn.sprite = function(opts) {
    
    opts = $.extend({},$.sprite.defaults, opts || {});
    $(this).each(function(){
        var spec = ($(this).attr('sprite-src') || opts.img_spec).split("|");
        var img = spec[0], idx = spec[1];
        var info = $.extend(opts.info || $.sprite.info[img] || {}, $.sprite.info.defaults);
        
        $(this).css({
            'background-image':'url('+ (info.img_full_path || (opts.img_prefix + img + opts.img_suffix)) +')',
            'background-position': -(info.img_width * idx) % info.sprite_width + 'px '
                + (-info.img_height * Math.floor((info.img_width * idx) / info.sprite_width)) + 'px',
            width: info.img_width+'px',
            height: info.img_height+'px',
            padding: '0' // we don't want padding, it interferes with clipping!
            // TODO: make this more robust, like alter position and size of clipping to accomodate user-set padding.
        });
    });
};
